package com.dwxt.cdms.admin.controller;

import com.dwxt.cdms.admin.service.RoleServiceAdmin;
import com.dwxt.cdms.admin.service.UserRoleServiceAdmin;
import com.dwxt.cdms.entity.AdminUserRole;
import com.dwxt.cdms.entity.Role;
import com.dwxt.cdms.entity.UserRole;
import com.dwxt.cdms.entity.dto.RoleDTO;
import com.dwxt.common.annotation.ValidateFiled;
import com.dwxt.common.annotation.ValidateGroup;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/cdms/role")
public class RoleControllerAdmin {

    @Autowired
    private RoleServiceAdmin roleServiceAdmin;

    @Autowired
    private UserRoleServiceAdmin userRoleServiceAdmin;

    /**
     * @param roleDTO(顶级菜单Id,权限种类)
     * @return
     */
    @PostMapping("/createOrUpdateRole")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, filedName = "name", notNull = true),
            @ValidateFiled(index = 0, filedName = "menuIds", notNull = true),
    })
    public BaseResult createOrUpdateRole(RoleDTO roleDTO) {
        return roleServiceAdmin.createOrUpdateRole(roleDTO);
    }

    @DeleteMapping("/delete")
    public BaseResult delete(Integer id) {
        if (id == 1||id==3||id==4||id==5||id == 9||id == 13) {
            return BaseResult.build(StatusCode.CAN_NOT_DELETE_FIXED_ROLE);
        }
        List<UserRole> userRoles = userRoleServiceAdmin.selectByRoleId(id);
        if (!userRoles.isEmpty()) {
            return BaseResult.build(StatusCode.ROLE_IS_USED);
        } else {
            int i = roleServiceAdmin.deleteByPrimaryKey(id);
            return i == 0 ? BaseResult.build(StatusCode.ROLE_NOT_EXIST) : BaseResult.ok();
        }
    }


    @GetMapping("/pageList")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, notNull = true),
            @ValidateFiled(index = 1, notNull = true),
    })
    public BaseResult pageList(Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        return roleServiceAdmin.selectAllRoleVo();
    }

    /**
     * 获取所有角色
     *
     * @return
     */
    @GetMapping("/all")
    public BaseResult all() {
        List<Role> roles = roleServiceAdmin.selectAllRole();
        return BaseResult.ok(roles);
    }




}
